#include "TcpConnection.h"
#include "TcpServer.h"
#include "Threadpool.h"
#include <iostream>
#include <functional>
using namespace std;
class Mytask{
public:
Mytask(const string &msg,TcpConnectionPtr conn)
:_msg(msg)
,_conn(conn){}
void process(){
    //发送消息的操作要交给一个TCP连接来做
    //但是此操作不能放在计算线程中，所以要通知IO线程
    _conn->sendinLoop(_msg);
}
private:
string _msg;
TcpConnectionPtr _conn;
};
class EchoServer
{
public:
    EchoServer(unsigned short port, string ip, int threadNum, int queSize)
        : _threadpool(threadNum, queSize), _server(port, ip)
    {
        printf("EchoServer\n");
        using namespace std::placeholders;
        _server.setAllCallbacks(
            std::bind(&EchoServer::onConnection, this, _1),
            std::bind(&EchoServer::onMessage, this, _1),
            std::bind(&EchoServer::onClose, this, _1));
    }
    void start()
    {
        _threadpool.start();
        _server.start();
    }

private:
    void onConnection(TcpConnectionPtr conn)
    {
        cout << conn->toString() << " has connected successfully.\n";
    }

    void onMessage(TcpConnectionPtr conn)
    {

        string msg = conn->receive(); // 不能阻塞
        cout << "recv: " << msg << endl;
        Mytask task(msg, conn);
        _threadpool.addTask(std::bind(&Mytask::process, task));
        // 当计算线程处理完毕之后，再交给IO线程进行发送

    }

    void onClose(TcpConnectionPtr conn)
    {
        cout << conn->toString() << " has closed." << endl;
    }

private:
    Threadpool _threadpool;
    TcpServer _server;
};
int main(){
    EchoServer server(8000,"0.0.0.0",4,10);
    server.start();
}